import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Space,
  Input,
  Radio,
  Upload,
  Modal,
  message
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import styles from './index.module.scss'
import Channel from 'components/Channel'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import { baseURL } from 'utils/request'
import { addArticles, getArticle, updataArticles } from 'api/acticle'
export default class ArticlePublish extends Component {
  state = {
    type: 1,
    fileList: [],
    showProview: false,
    previewUrl: '',
    id: this.props.match.params.id
  }
  formRef = React.createRef()
  render() {
    return (
      <div className={styles.publish}>
        <Card
          title={
            <Breadcrumb>
              <Breadcrumb.Item>
                <Link to="/home">首页</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>
                {this.state.id ? '修改文章' : '发布文章'}
              </Breadcrumb.Item>
            </Breadcrumb>
          }
        >
          <Form
            ref={this.formRef}
            onFinish={this.onFinish}
            labelCol={{ span: 4 }}
            size="large"
            validateTrigger={['onBlur', 'onChange']}
            initialValues={{
              content: '',
              type: this.state.type
            }}
          >
            <Form.Item
              label="标题"
              name="title"
              rules={[{ required: true, message: '文章的标题不能为空' }]}
            >
              <Input
                style={{ width: 400 }}
                placeholder="请输入文章的标题"
              ></Input>
            </Form.Item>
            <Form.Item
              label="频道"
              name="channel_id"
              rules={[{ required: true, message: '文章的频道不能为空' }]}
            >
              <Channel></Channel>
            </Form.Item>
            <Form.Item label="封面" name="type">
              <Radio.Group onChange={this.onChangeType} value={this.state.type}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {this.state.type !== 0 && (
              <Form.Item wrapperCol={{ offset: 4 }}>
                {/*// fileList: 控制文件列表
                   // action: 控制上传的url 保证是一个完整的url
                   // name： 用于指定名字 */}
                <Upload
                  listType="picture-card"
                  name="image"
                  fileList={this.state.fileList}
                  action={`${baseURL}upload`}
                  onChange={this.uploadImage}
                  onPreview={this.handlePreview}
                  beforeUpload={this.beforeUpload}
                >
                  {this.state.fileList.length < this.state.type && (
                    <PlusOutlined />
                  )}
                </Upload>
              </Form.Item>
            )}

            <Form.Item
              label="内容"
              name="content"
              rules={[{ required: true, message: '文章的内容不能为空' }]}
            >
              <ReactQuill theme="snow" placeholder="请输入文章内容..." />
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 4 }}>
              <Space>
                <Button type="primary" htmlType="submit">
                  {this.state.id ? '修改文章' : '发布文章'}
                </Button>
                <Button onClick={this.addDraft}>存入草稿</Button>
              </Space>
            </Form.Item>
          </Form>
        </Card>
        <Modal
          visible={this.state.showProview}
          footer={null}
          title={'图片预览'}
          onCancel={this.handleCancel}
        >
          <img
            alt="example"
            style={{ width: '100%' }}
            src={this.state.previewUrl}
          />
        </Modal>
      </div>
    )
  }
  async save(values, draft) {
    const { fileList, type } = this.state
    if (fileList.length !== type) {
      return message.warn('上传的图片数量不正确')
    }
    // 根据fileList得到
    const images = fileList.map(item => {
      return item.url || item.response.data.url
    })
    console.log(images)
    if (this.state.id) {
      // 修改文章
      await updataArticles(
        {
          ...values,
          cover: {
            type,
            images
          },
          id: this.state.id
        },
        draft
      )
      message.success('修改成功')
    } else {
      // 添加文章
      await addArticles(
        {
          ...values,
          cover: {
            type,
            images
          }
        },
        draft
      )
      message.success('添加成功')
    }

    this.props.history.push('/home/list')
  }
  // 发布
  onFinish = async values => {
    this.save(values, false)
  }
  // 新增
  addDraft = async () => {
    const values = await this.formRef.current.validateFields()
    this.save(values, true)
  }
  onChangeType = e => {
    this.setState({
      type: e.target.value,
      fileList: []
    })
  }
  // 上传文件
  uploadImage = ({ fileList }) => {
    this.setState({
      fileList
    })
  }
  // 预览
  handlePreview = file => {
    const url = file.url || file.response.data.url
    this.setState({
      showProview: true,
      previewUrl: url
    })
  }
  // 关闭预览
  handleCancel = () => {
    this.setState({
      showProview: false,
      previewUrl: ''
    })
  }
  // 上传校验
  beforeUpload = file => {
    if (!['image/png', 'image/jpeg'].includes(file.type)) {
      message.warn('只能上传jpg或者png的图片')
      return Upload.LIST_IGNORE
    }
    if (file.size >= 1024 * 500) {
      message.warn('请上传小于500kb的图片')
      return Upload.LIST_IGNORE
    }
    return true
  }

  async componentDidMount() {
    if (this.state.id) {
      const res = await getArticle(this.state.id)
      console.log(res)
      const values = {
        ...res.data,
        type: res.data.cover.type
      }
      // 表单设置默认值
      this.formRef.current.setFieldsValue(values)
      const fileList = res.data.cover.images.map(item => {
        return {
          url: item
        }
      })
      this.setState({
        fileList,
        type: res.data.cover.type
      })
    }
  }
}
